import Vue from 'vue'
import store from '../store'
import VueRouter from 'vue-router'
import { cloneDeep } from 'lodash'
import { setCacheTagsViewRoutes } from '@/utils/tags'
import { formatRoutes } from '@/utils/common'
import Layout from '@/layout/index'
// 解决 `element ui` 导航栏重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

/* Router Modules */
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
let moduleArr = []
modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  // const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  // modules[moduleName] = value.default
  if (Array.isArray(value.default)) {
    moduleArr = moduleArr.concat(value.default)
    return
  }
  moduleArr.push(value.default)
}, {})

/**
 * Note: sub-menu only appear when route children.length >= 1
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar
    keepAlive: true              if set true, the page will no be cached(default is false)
    affix: true                  if set true, the tag will affix in the tags-view
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * _constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export let constantRoutes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/404',
    name: 'notFound',
    component: () => import('@/views/error/404.vue'),
    meta: {
      title: '找不到此页面'
    }
  },
  {
    path: '/401',
    name: 'noPower',
    component: () => import('@/views/error/401.vue'),
    meta: {
      title: '没有权限'
    }
  }
]

// 未通过接口请求获得路由数据时使用
if (!store.state.themeConfig.themeConfig.isConnect) {
  // 菜单路由集合
  const routes = [
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/home'),
      meta: {
        affix: true,
        title: 'message.router.home',
        auth: ['admin', 'test'],
        icon: 'iconfont icon-shouye'
      }
    },
    ...moduleArr
  ]
  // set routes
  store.dispatch('routesList/setRoutesList', routes)
  // set roles
  store.commit('userInfos/SET_ROLES', ['admin'])
  // 页面渲染路由集合
  constantRoutes = [
    {
      path: '/',
      redirect: '/home',
      component: Layout,
      children: formatRoutes(cloneDeep(routes))
    },
    ...constantRoutes
  ]
  // set tags
  setCacheTagsViewRoutes(JSON.parse(JSON.stringify(routes)))
}

/**
 * asyncRoutes
 * the routes that need to be dynamically loaded based on user roles
 */
export const asyncRoutes = [
  /** when your routing map is too long, you can split it into small modules **/
  // accountRouter,
  // 404 page must be placed at the end !!!
  ...moduleArr,
  { path: '*', redirect: '/404' }
]

// 加载静态路由
const createRouter = () =>
  new VueRouter({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
  })

// 创建路由
const router = createRouter()

// 重置路由
export const resetRouter = () => {
  router.matcher = createRouter().matcher
}

// 导出路由
export default router
